import { ref, reactive } from 'vue'

// 全局预约数据状态
const bookingList = ref([])
const isLoading = ref(false)

// 预约统计信息
const bookingStats = reactive({
  total: 0,
  pending: 0,
  completed: 0,
  cancelled: 0
})

// 生成新的预约记录ID
const generateBookingId = () => {
  return 'booking_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
}

// 添加新的预约记录
const addBooking = (bookingInfo, roomInfo) => {
  const newBooking = {
    id: generateBookingId(),
    date: bookingInfo.date,
    houseId: bookingInfo.houseId,
    img: roomInfo.housePicture || '/src/assets/imgs/room_text_bg.png',
    title: roomInfo.houseTitle || '房源标题',
    subTitle: roomInfo.address || '房源地址',
    distanceInfo: roomInfo.distanceInfo || null,
    rentPrice: roomInfo.rentPriceListing || '0',
    tags: roomInfo.tags || [],
    comment: bookingInfo.comment || '无备注',
    status: '待看房',
    createTime: `${bookingInfo.date} 全天 间时有空`
  }
  
  // 添加到列表开头
  bookingList.value.unshift(newBooking)
  
  // 更新统计
  updateStats()
  
  console.log('添加新预约记录:', newBooking)
  return newBooking
}

// 移除预约记录
const removeBooking = (bookingId) => {
  const index = bookingList.value.findIndex(item => item.id === bookingId)
  if (index > -1) {
    const removed = bookingList.value.splice(index, 1)[0]
    updateStats()
    console.log('移除预约记录:', removed)
    return removed
  }
  return null
}

// 更新预约记录
const updateBooking = (bookingId, updates) => {
  const index = bookingList.value.findIndex(item => item.id === bookingId)
  if (index > -1) {
    bookingList.value[index] = { ...bookingList.value[index], ...updates }
    updateStats()
    return bookingList.value[index]
  }
  return null
}

// 设置预约列表
const setBookingList = (list) => {
  bookingList.value = list || []
  updateStats()
}

// 更新统计信息
const updateStats = () => {
  bookingStats.total = bookingList.value.length
  bookingStats.pending = bookingList.value.filter(item => item.status === '待看房').length
  bookingStats.completed = bookingList.value.filter(item => item.status === '已完成').length
  bookingStats.cancelled = bookingList.value.filter(item => item.status === '已取消').length
}

// 获取预约记录
const getBooking = (bookingId) => {
  return bookingList.value.find(item => item.id === bookingId)
}

// 清空预约列表
const clearBookingList = () => {
  bookingList.value = []
  updateStats()
}

// 设置加载状态
const setLoading = (loading) => {
  isLoading.value = loading
}

// 导出状态和方法
export {
  // 状态
  bookingList,
  isLoading,
  bookingStats,
  
  // 方法
  addBooking,
  removeBooking,
  updateBooking,
  setBookingList,
  getBooking,
  clearBookingList,
  setLoading,
  updateStats
}
